import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:speed_random/core/http/ws_app_test.dart';

class DebugPage extends StatefulWidget {
  const DebugPage({Key? key}) : super(key: key);

  @override
  State<DebugPage> createState() => _DebugPageState();
}

class _DebugPageState extends State<DebugPage> {
  late TextEditingController _urlCtrl;
  late TextEditingController _msgCtrl;

  @override
  void initState() {
    super.initState();
    _urlCtrl = TextEditingController();
    _loadUrl();
  }

  Future<void> _loadUrl() async {
    final prefs = await SharedPreferences.getInstance();
    final saved = prefs.getString('debugWsUrl') ?? 'ws://192.168.3.20:8080/ws';
    _urlCtrl.text = saved;
  }

  Future<void> _saveAndConnect() async {
    final url = _urlCtrl.text.trim();
    if (url.isEmpty) return;
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('debugWsUrl', url);

    // 重新初始化 ws
    await wsPrintInit(url);
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('已保存并连接')),
      );
    }
  }



  /// 清空缓存
  void clearCache() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear();

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('清空缓存  ok')),
    );
  }

  void _sendMsg() {

    wsPrint("测试发送", type: 'debug');
  }

  @override
  void dispose() {
    _urlCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Debug 工具')),
      body: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            TextField(
              controller: _urlCtrl,
              decoration: const InputDecoration(
                labelText: 'WebSocket 地址',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            SizedBox(
              width: double.infinity,
              child: ElevatedButton(
                onPressed: _saveAndConnect,
                child: const Text('连接'),
              ),
            ),
            const SizedBox(height: 24),

            Row(
              children: [
                ElevatedButton(
                onPressed: _sendMsg,
                child: const Text('发送测试文本'),
              ),

                const SizedBox(width: 24),
                ElevatedButton(
                  onPressed: clearCache,
                  child: const Text('清空缓存'),
                ),
              ],
            )

,
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('返回'),
            ),

          ],
        ),
      ),
    );
  }
}
